import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common/constants.dart';
import '../common/images.dart';
import '../common/routes.dart';
import '../controllers/login_controller.dart';

class LoginPage extends StatelessWidget {
  final LoginController controller = Get.find<LoginController>();

  LoginPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black54,
      resizeToAvoidBottomInset: false,
      body: Column(
        children: [
          Expanded(
            child: GestureDetector(
                child: Container(color: Colors.transparent),
                onTap: () {
                  Get.back();
                }),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(16),
                topRight: Radius.circular(16),
              ),
            ),
            width: double.infinity,
            child: _buildLoginContent(),
          ),
        ],
      ),
    );
  }

  Widget _buildLoginContent() {
    return Column(
      children: [
        Row(
          children: [
            Obx(
              () => controller.isPhoneLogin.value
                  ? IconButton(
                      style: IconButton.styleFrom(padding: const EdgeInsets.all(0)),
                      onPressed: () {
                        controller.isPhoneLogin.value = false;
                      },
                      icon: Icon(
                        CupertinoIcons.chevron_left,
                        color: Colors.grey[400],
                        size: 20,
                      ),
                    )
                  : SizedBox.shrink(),
            ),
            Spacer(),
            IconButton(
              style: IconButton.styleFrom(padding: const EdgeInsets.all(0)),
              onPressed: () {
                Get.back();
              },
              icon: Image.asset(Images.popup_close, width: 32, height: 32, fit: BoxFit.cover),
            )
          ],
        ),
        Text(
          "登录",
          style: TextStyle(fontSize: 24),
        ),
        const SizedBox(height: 10),
        Obx(() => controller.isPhoneLogin.value ? _buildPhoneLoginView() : _buildLoginView()),
        const SizedBox(height: 10),
        _buildAgreementRow(),
        const SizedBox(height: 30),
        _buildOtherLoginOptions(),
        Obx(() {
          return AnimatedCrossFade(
            firstChild: SizedBox.shrink(),
            secondChild: SizedBox(height: 90),
            crossFadeState: controller.keyboardHeight.value > 0 ? CrossFadeState.showSecond : CrossFadeState.showFirst,
            duration: Duration(milliseconds: 250),
          );
        })
      ],
    );
  }

  Widget _buildPhoneLoginView() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Column(
        children: [
          _buildPhoneNumberField(),
          const SizedBox(height: 10),
          _buildPasswordField(),
          const SizedBox(height: 20),
          _buildLoginButton(),
        ],
      ),
    );
  }

  _showPrivacyDialog() {
    Get.defaultDialog(
      barrierDismissible: false,
      title: '用户登录指引协议',
      titleStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
      titlePadding: const EdgeInsets.only(top: 24, bottom: 16),
      content: RichText(
        text: TextSpan(text: '为了更好的保障你的权益，请阅读并同意', style: const TextStyle(color: Colors.black, fontSize: 15), children: <TextSpan>[
          TextSpan(
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  Get.toNamed(Routes.WEB, arguments: {'title': '隐私政策', 'url': 'https://m.imusic.cn/h5/privacy_policy_page'});
                },
              text: '《隐私政策》',
              style: TextStyle(color: Constants.themeColor)),
          const TextSpan(text: '和'),
          TextSpan(
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  Get.toNamed(Routes.WEB, arguments: {'title': '用户协议', 'url': 'https://m.imusic.cn/imapp/wangzpicy'});
                },
              text: '《用户协议》',
              style: TextStyle(color: Constants.themeColor))
        ]),
      ),
      contentPadding: const EdgeInsets.fromLTRB(16, 0, 16, 5),
      confirm: Container(
        width: 120,
        margin: const EdgeInsets.only(bottom: 16),
        child: FilledButton(
          onPressed: () {
            controller.isChecked.value = true;
            controller.loginAsGuest();
            Get.back();
          },
          style: FilledButton.styleFrom(
            backgroundColor: Constants.themeColor,
            padding: const EdgeInsets.symmetric(horizontal: 8),
          ),
          child: Text(
            '同意并登录',
            style: TextStyle(color: Colors.white, fontSize: 16),
          ),
        ),
      ),
      cancel: Container(
        width: 120,
        margin: const EdgeInsets.only(bottom: 16),
        child: FilledButton(
          onPressed: () {
            Get.back();
          },
          style: FilledButton.styleFrom(
            backgroundColor: Colors.grey[300],
            padding: const EdgeInsets.symmetric(horizontal: 8),
          ),
          child: Text(
            '不同意',
            style: TextStyle(color: Colors.black, fontSize: 16),
          ),
        ),
      ),
    );
  }

  Widget _buildLoginView() {
    return Column(
      children: [
        Row(children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: TextButton(
                onPressed: () {
                  controller.isPhoneLogin.value = true;
                },
                style: TextButton.styleFrom(
                  backgroundColor: Constants.themeColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                child: const Text('手机号登录', style: TextStyle(fontSize: 15, color: Colors.white)),
              ),
            ),
          )
        ]),
        const SizedBox(height: 10),
        Row(children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: TextButton(
                onPressed: () {
                  if (controller.isChecked.value) {
                    controller.loginAsGuest();
                  } else {
                    _showPrivacyDialog();
                  }
                },
                style: TextButton.styleFrom(
                  backgroundColor: Colors.grey[200],
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                child: const Text('游客登录', style: TextStyle(fontSize: 15, color: Colors.black)),
              ),
            ),
          )
        ]),
      ],
    );
  }

  Widget _buildOtherLoginOptions() {
    return Column(
      children: [
        Row(children: [
          Expanded(
            flex: 1,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Divider(height: 0.5, color: Colors.grey[200]),
            ),
          ),
          const Text(
            '更多登录方式',
            style: TextStyle(color: Colors.black26, fontSize: 13),
          ),
          Expanded(
            flex: 1,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Divider(height: 0.5, color: Colors.grey[200]),
            ),
          ),
        ]),
        const SizedBox(height: 20),
        Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          IconButton(
            onPressed: () {},
            style: IconButton.styleFrom(
              padding: const EdgeInsets.all(0),
            ),
            icon: Image.asset(Images.wechat_login, width: 50, height: 50, fit: BoxFit.cover),
          ),
          Container(width: 15),
          IconButton(
            onPressed: () {},
            style: IconButton.styleFrom(
              padding: const EdgeInsets.all(0),
            ),
            icon: Image.asset(Images.qq_login, width: 50, height: 50, fit: BoxFit.cover),
          ),
          Container(width: 15),
          IconButton(
            onPressed: () {},
            style: IconButton.styleFrom(
              padding: const EdgeInsets.all(0),
            ),
            icon: Image.asset(Images.apple_login, width: 50, height: 50, fit: BoxFit.cover),
          ),
        ]),
        const SizedBox(height: 50),
      ],
    );
  }

  Widget _buildAgreementRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        GestureDetector(
          child: Obx(() => Image.asset(controller.isChecked.value ? Images.checkbox_selected : Images.checkbox_normal, width: 25, height: 25, fit: BoxFit.cover)),
          onTap: () {
            controller.toggleCheck();
          },
        ),
        RichText(
          text: TextSpan(text: '我已阅读并同意', style: const TextStyle(color: Colors.black, fontSize: 13), children: <TextSpan>[
            TextSpan(
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Get.toNamed(Routes.WEB, arguments: {'title': '隐私政策', 'url': 'https://m.imusic.cn/h5/privacy_policy_page'});
                  },
                text: '《隐私政策》',
                style: TextStyle(color: Constants.themeColor)),
            const TextSpan(text: '和'),
            TextSpan(
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Get.toNamed(Routes.WEB, arguments: {'title': '用户协议', 'url': 'https://m.imusic.cn/imapp/wangzpicy'});
                  },
                text: '《用户协议》',
                style: TextStyle(color: Constants.themeColor))
          ]),
        )
      ],
    );
  }

  Widget _buildPhoneNumberField() {
    return TextField(
      keyboardType: TextInputType.phone,
      controller: controller.phoneNumberController,
      style: const TextStyle(fontSize: 15.0, color: Colors.black),
      cursorColor: Constants.themeColor,
      decoration: InputDecoration(
        hintText: "请输入手机号",
        hintStyle: const TextStyle(fontSize: 15.0, color: Colors.black38),
        filled: true,
        fillColor: const Color(0xFFF5F5F5),
        isCollapsed: true,
        contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
          borderSide: BorderSide(color: Constants.themeColor, width: 1),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
          borderSide: BorderSide(color: Colors.white, width: 0),
        ),
        suffix: Obx(() => controller.showSuffix.value
            ? GestureDetector(
                onTap: () {
                  controller.startCountdown();
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 5.0),
                  child: Text(
                    controller.secondsRemaining.value > 0 ? '${controller.secondsRemaining.value}s后重新发送' : "获取验证码",
                    style: TextStyle(fontSize: 15.0, color: controller.secondsRemaining.value > 0 ? Constants.themeColor.withAlpha(127) : Constants.themeColor),
                  ),
                ),
              )
            : SizedBox.shrink()),
      ),
    );
  }

  Widget _buildPasswordField() {
    return TextField(
      keyboardType: TextInputType.number,
      controller: controller.passwordController,
      style: const TextStyle(fontSize: 15.0, color: Colors.black),
      cursorColor: Constants.themeColor,
      decoration: InputDecoration(
        hintText: "请输入验证码",
        hintStyle: const TextStyle(fontSize: 15.0, color: Colors.black38),
        filled: true,
        fillColor: const Color(0xFFF5F5F5),
        isCollapsed: true,
        contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        focusedBorder: OutlineInputBorder(
          borderRadius: const BorderRadius.all(
            Radius.circular(10.0),
          ),
          borderSide: BorderSide(color: Constants.themeColor, width: 1),
        ),
        enabledBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
          borderSide: BorderSide(color: Colors.white, width: 0),
        ),
      ),
    );
  }

  Widget _buildLoginButton() {
    return Row(
      children: [
        Expanded(
          child: TextButton(
            onPressed: () {
              Get.back();
            },
            style: TextButton.styleFrom(
              backgroundColor: Constants.themeColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
            ),
            child: const Text('登录', style: TextStyle(fontSize: 16, color: Colors.white)),
          ),
        ),
      ],
    );
  }
}
